//
//  ExaminationQuestionViewController.m
//  SafeFoodManagerDemo
//
//  Created by ios-1 on 2018/3/7.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "ExaminationQuestionViewController.h"
#import "PatrolTableViewCell.h"
#import "QuestionsTableViewCell.h"
#import "QuestionsModel.h"
#import "LoginStatuesModel.h"

#import "SendPatrolViewController.h"
#import "AddRecruitViewController.h"
#import "AnswerQuestionsViewController.h"
@interface ExaminationQuestionViewController ()
@property(nonatomic,copy)NSString*SearchKeyWord;
@property(nonatomic,copy)NSString*positionId;      //当前岗位ID
@property(nonatomic,copy)NSString*shopId;          //当前岗位商户ID
@property(nonatomic,assign)BOOL is_selectPosition; //是否点击当前岗位
@property(nonatomic,strong) QuestionsModel *questionModel;
@property(nonatomic,strong) UILabel *headcontentLab;
@property(nonatomic,strong)NSMutableArray *data1Arr;

@end

@implementation ExaminationQuestionViewController{
    BOOL isScal;
    NSInteger _section;
    
    
  
}
-(NSMutableArray*)data1Arr
{
    if (!_data1Arr) {
        
        _data1Arr=[NSMutableArray array];
    }
    
    return _data1Arr;
}


- (void)viewDidLoad {
    _section = 99;
    isScal = false;
    [super viewDidLoad];
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"QuestionsTableViewCell" bundle:nil] forCellReuseIdentifier:@"QuestionCell"];
    self.homeTableView.tableHeaderView = [self tabHeadView];
    self.homeTableView.mj_footer.hidden = YES;
    [self.homeTableView.mj_header beginRefreshing];
    
    //监听答题/阅卷的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(answernote) name:@"answernote" object:nil];
}
- (void)answernote
{
    [self.homeTableView.mj_header beginRefreshing];
}

- (UIView*)tabHeadView
{
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    headview.backgroundColor = [UIColor clearColor];
    
    UIView *baseview = [[UIView alloc]initWithFrame:CGRectMake(0, 10, kScreenWidth, 80)];
    baseview.backgroundColor = [UIColor whiteColor];
    [headview addSubview:baseview];
    
    UILabel *labline = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, kScreenWidth, 1)];
    labline.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [baseview addSubview:labline];
    
    UILabel *titlelab = [[UILabel alloc]initWithFrame:CGRectMake((kScreenWidth-80)/2, 20, 80, 20)];
    titlelab.backgroundColor = [UIColor whiteColor];
    titlelab.textColor = [UIColor darkTextColor];
    titlelab.font = [UIFont systemFontOfSize:16];
    titlelab.textAlignment = NSTextAlignmentCenter;
    titlelab.text = @"考试须知";
    [baseview addSubview:titlelab];
    
    UILabel *contentlab = [[UILabel alloc]initWithFrame:CGRectMake(10, 40, kScreenWidth-20, 40)];
    contentlab.backgroundColor = [UIColor whiteColor];
    contentlab.textColor = [UIColor darkTextColor];
    contentlab.font = [UIFont systemFontOfSize:14];
    contentlab.text = @"内部员工考试";
    [baseview addSubview:self.headcontentLab = contentlab];
    return headview;
}
#pragma mark-tablevie代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    NSLog(@"shua___%ld---#__%ld",(long)section,(long)_section);
    QuestionsItemData *itemData = self.dataArr[section];
    
//    if (isScal == false) {
//
//        QuestionsItemData *itemData = self.dataArr[section];
//     return    itemData.item.count;
//
//       // return self.dataArr[section].con
//    }else{
//        if ((section = _section)) {
//
//            return 0;
//
//        }else{
//        QuestionsItemData *itemData = self.dataArr[section];
//
//        }
//
//    }
     return    itemData.item.count;
    
   // return isScal ==false? itemData.item.count:0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QuestionsTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"QuestionCell" forIndexPath:indexPath];
    if(self.dataArr.count){
        QuestionsItemData *itemdata = self.dataArr[indexPath.section];
        QuestionsItem *item= itemdata.item[indexPath.row];
        
        [cell refreshData:itemdata item:item];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnswerQuestionsViewController *answer = [AnswerQuestionsViewController new];
    QuestionsItemData *itemdata = self.dataArr[indexPath.section];
    QuestionsItem *item= itemdata.item[indexPath.row];
    
    answer.paperItemId = [NSString stringWithFormat:@"%zd",item.paperItemId];
    answer.itemType = item.itemType;
    answer.dataArray = self.dataArr;
    [self.navigationController pushViewController:answer animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    QuestionsItemData *itemdata = self.dataArr[section];
    
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    headview.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth-20, 30)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor darkGrayColor];
    label.font = [UIFont systemFontOfSize:15];
    label.text = itemdata.name;
    
    UIButton *button = [[UIButton alloc]init];
    button.frame = label.bounds;
    //button.backgroundColor = [UIColor orangeColor];
    
    button.tag = section;
   // [button addTarget:self action:@selector(scal:) forControlEvents:UIControlEventTouchUpInside];
    //[label addSubview:button];
    [headview addSubview:label];
   // [headview addSubview:button];
//    UITapGestureRecognizer *tapRecognizerWeibo = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scal:)];
//
//    headview.userInteractionEnabled=YES;
//    [headview addGestureRecognizer:tapRecognizerWeibo];
    return headview;
}

-(void)scal:(UIButton*)btn{
    NSLog(@"%ld",(long)btn.tag);
   NSInteger c = btn.tag;
    
    isScal = !isScal;
    
    
    _section = btn.tag;
    
    
    if (isScal) {
        QuestionsItemData *itemdata = self.dataArr[_section];
        
        itemdata.item = nil;
        
    }else{
        
        self.dataArr = [self.data1Arr copy];
        
    }
    [self.homeTableView reloadData];

    
}




-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
    view.tintColor=TBColorTableViewBg;
    
}

#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:PatrolListType];

    if (isSelf) {
        
        if ([self.Reqmodel.ptype isEqualToString:@"1"]) {
            
            Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
            
        }else if ([self.Reqmodel.ptype isEqualToString:@"2"])
        {
            
            NSArray *PostArr= [USER_DEFAULT objectForKey:@"TBChoose"];//如果本地存在则读取本地的
            
            if (PostArr.count!=0) {
                
                Choose.CustomArr=PostArr;
                
            }else{
                
                Choose.CustomArr=@[@{@"fieldName":@"marketIds",@"name":@"开办方",@"value":@""},@{@"fieldName":@"type",@"name":@"",@"value":@""},@{@"fieldName":@"checkUserIds",@"name":@"检查员",@"value":@""},@{@"fieldName":@"startDate",@"name":@"开始日期",@"value":@""},@{@"fieldName":@"endDate",@"name":@"结束日期",@"value":@""}];
            }
        }
        
    }else{
        
        Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
    }
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
    Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.Reqmodel.params=paras;
        
        self.SearchKeyWord=keyword;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}

#pragma mark-新增事件

//搜索的跳转事件，可以删除。
-(void)addNewgoods
{
    int k =0; int h =0;
    for(int i =0; i<self.dataArr.count;i++)
    {
        QuestionsItemData *itemdata = self.dataArr[i];
        
        for(int j=0;j<itemdata.item.count;j++)
        {
            QuestionsItem *item= itemdata.item[j];
            if(item.isAnswer == 0)
            {
                k++;
            }
            if(item.isMark == 0)
            {
                h++;
            }
        }
    }
    if(k > 0 || h >0)
    {
        NSString *message = [LoginStatuesModel getUserType] ==4?[NSString stringWithFormat:@"尚有%zd道题未阅，是否确认封卷",h]:[NSString stringWithFormat:@"尚有%zd道题未答，是否确认交卷",k];
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:message cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex==1) {
                [self httpData];
            }
        }];
    }else{
        [self httpData];
    }
}

- (void)httpData
{
    if([LoginStatuesModel getUserType] == 4)
    {
        [self SealedHttp];//考官封卷
    }else
        [self AssignmentHttp];//考生交卷
}
#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
}

/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
//    self.Reqmodel.currentPage++;
//
//    [self loadDatas];
    [self mjEndRefreshing:self.homeTableView];
}


-(void)loadDatas
{
    [self showLoadingAnimation];
    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:self.paperId forKey:@"paperId"];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/paperItemList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        self.questionModel=[QuestionsModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            //请求成功
            if(self.questionModel.data.itemData.count){
                if(self.Reqmodel.currentPage==1)
                {
                    [self.dataArr removeAllObjects];
                }
                [self.dataArr addObjectsFromArray:self.questionModel.data.itemData];
                self.headcontentLab.text = self.questionModel.data.intro;
                [self.homeTableView reloadData];
                self.data1Arr = [self.dataArr copy];
                
            }else{
                self.Type=TBNODateType;
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}

//考生交卷
-(void)AssignmentHttp
{
    [self showLoadingAnimation];
    
    NSString *staffId = [NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.paperId forKey:@"paperId"];
    [params setObject:staffId forKey:@"staffId"];

    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/paperAnswerSubmit.json" andrequestTime:5 andParams:params andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            //注册交卷的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Assignmentnote" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else if (responseStatus==0||responseStatus==2)
        {
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
            }];
        }
        
    }];
}

//考官封卷
- (void)SealedHttp
{
    [self showLoadingAnimation];
    
    NSString *staffId = [NSString stringWithFormat:@"%ld",[LoginStatuesModel getStaffId]];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.paperId forKey:@"paperId"];
    [params setObject:staffId forKey:@"staffId"];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/paperMarkSubmit.json" andrequestTime:5 andParams:params andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            //请求成功
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            //注册封卷的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Assignmentnote" object:nil];
            [self.navigationController popViewControllerAnimated:YES];

        }else if (responseStatus==0||responseStatus==2)
        {
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
